package com.ling.map
{
	import com.ling.brushes.view.BaseGridBrush;
	import com.ling.denfind.EditorDfined;
	
	import flash.events.MouseEvent;
	
	import mx.flash.UIMovieClip;
	
	import spark.components.Group;
	
	public class GridMap extends Group
	{
		public var level:uint;
		private var gridContainer:UIMovieClip;
		private var gridArr:Vector.<BgGrid>;
		
		public function GridMap(w:uint = 9,h:uint = 9)
		{
			super();
			
			EditorDfined.W_NUM = w;
			EditorDfined.H_NUM = h;
			
			gridArr = new Vector.<BgGrid>();
			
			gridContainer = new UIMovieClip();
			initGrids();
		}
		
		public function destroy():void
		{
			(this.parent as Group).removeElement(this);
			gridContainer = null;
			for each(var i:BgGrid in gridArr)
			{
				i.removeEventListener(MouseEvent.CLICK,clickGrid);
			}
			gridArr = null;
		}
		
		
		private function initGrids():void
		{
			for(var i:uint = 0;i<EditorDfined.W_NUM;i++)
			{
				for(var j:uint = 0;j<EditorDfined.H_NUM;j++)
				{
					var grid:BgGrid = new BgGrid();
					grid.column = i;
					grid.row = j;
					gridContainer.addChild(grid);
					gridArr.push(grid);
					grid.addEventListener(MouseEvent.CLICK,clickGrid);
				}
			}
			addElement(gridContainer);
		}
		
		private function clickGrid(event:MouseEvent):void
		{
			var grid:BgGrid = event.currentTarget as BgGrid;
			var brush:BaseGridBrush = MainManager.brushCon.brush;
			if(brush)
			{
				grid.type = brush.type;
			}
		}
		
		
		public function getXML():XML
		{
			var x:XML = <grids/>;
			for each(var i:BgGrid in gridArr)
			{
				x.appendChild(i.getXML());
			}
			
			return x;
		}
	}
}